
package firewatig

/** class that talks JSSH to Firefox */
class JSSH {
	
	Socket socket = new Socket("localhost", 9997);
	
	JSSH(){
	     //sync up input/output
		say('');

		say("""
	            function println(x) { print(x+"\\n"); }
				function doc() { return getWindows()[0].getBrowser().contentDocument; }
				function win() { return getWindows()[0].getBrowser().contentWindow; }
				function loadURI(a) { getWindows()[0].getBrowser().loadURI(a); }
				function trim(str){ return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*\$/, ''); }
				function findRegExp( tagName, attribute, attributeValuePattern ){
					regexp = new RegExp(attributeValuePattern);
					var tags = doc().getElementsByTagName(tagName);
					for(i=0;i<tags.length;i++){
						var av = tags[i].getAttribute(attribute);
						if (av && av.search(regexp) == 0 ){
							return tags[i];
						}
					}
					return null;
				}
				function findInsideContains(tagName, value ){
					var tags = doc().getElementsByTagName(tagName);
					println ("found "+tags.length+" tags")
					for(i=0;i<tags.length;i++){
						var tv = tags[i].innerHTML;
						println(" tag["+i+"] tv = "+tv);
						if ( tv.indexOf(value)!=-1)
							return tags[i]
					}
					return null;
				}
				function find(tag, how, what){
					var tags = doc().getElementsByTagName(tag);
					for(i=0;i<tags.length;i++){
						tag = tags[i]
						if ( tag.getAttribute(how) == what ){
							return tag
						}
					}
					return null;
				}
				function clickIt(fireOnThis){
					var evObj = doc().createEvent('MouseEvents');
					evObj.initEvent( 'click', true, true );
					fireOnThis.dispatchEvent(evObj);
				}
				print('burlap');""", 'burlap\n> ');

	}
	
	static boolean log = true;
	
	def say = {  command, stopSeq=null ->
		InputStream input = socket.inputStream
		OutputStream output = socket.outputStream
		def w = new PrintWriter(output)
		w << command
		if (!command.endsWith('\n')){
			w << ';\n';
	    	println "Sending: "+command+";"
		} else {
		    if (!stopSeq)
		    	println "Sending: "+command
		}
		
		w.flush()
		
		 //look for "\n> " sequence
		if(!stopSeq)
				stopSeq = "\n> "
		def loc = 0;
		def response = ""
		while(true){
			int x = input.read()
			if ( x == -1)
				return;
			char c = (char)x
			response += c
			if (log) {
				print c
				System.out.flush()
			}
			if ( x == stopSeq.charAt(loc)) {
				loc++
				if (loc==stopSeq.size()) {
					if ( input.available() != 0 ) {
						println "resetting."
						loc=0;
						continue;
					}
					return response.substring(0,response.size()-stopSeq.size())
				}
			} else {
				loc=0
			}
		}
		
	}

	def bwait = { 
			InputStream input = socket.inputStream
			OutputStream output = socket.outputStream
	
			while(true) {
				def x = say("getWindows()[0].getBrowser().webProgress.busyFlags");
				if (x=="0")
					break;
				println("Getting =>"+x+"<=")
				Thread.sleep(500)
			}
	}

	def clickIt = {
			InputStream input = socket.inputStream
			OutputStream output = socket.outputStream
	
		say(input, output, "clickIt(f)");
		bwait(input,output);
	}

}
